package com.camel.weixin.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author Administrator
 */
@Controller
@RequestMapping("/wx")
public class WeixinController {

    /**
     * 开发者通过检验signature对请求进行校验（下面有校验方式）。
     * 若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。加密/校验流程如下：
     * 1）将token、timestamp、nonce三个参数进行字典序排序
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     * 验证消息是否来自微信服务器
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串 校验成功后原样返回
     * @param response  响应
     * @return
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("/checkSignature")
    public void checkSignature(String signature, String timestamp, String nonce, String echostr, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
        PrintWriter out = response.getWriter();
        String token = "jfqpo6xurg";
        String[] arr = {token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuffer str = new StringBuffer("");
        for (String s : arr) {
            str.append(s);
        }
        MessageDigest instance = MessageDigest.getInstance("SHA-1");
        byte[] digest = instance.digest(str.toString().getBytes());
        String tmpStr = byteToStr(digest);
        System.out.println(signature);
        System.out.println(tmpStr);
        if (tmpStr.equals(signature.toUpperCase())) {
            out.write(echostr);
        }
        out.close();
        out = null;
    }

    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            strDigest.append(byteToHexStr(byteArray[i]));
        }
        return strDigest.toString();
    }


    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
}
